import { getCurrentTimestamp } from '../utils/time';
import {GNewsDao} from "@common/dao/g_news.dao";

export async function getNewsList(query: any, offset: number = 0, limit: number = 10) {
    // 缓存不存在，从数据库获取
    const result = await GNewsDao.getNewsList(offset, limit);
    return result;
}

export async function getNewsById(id: number) {
    // 缓存不存在，从数据库获取
    const result = await GNewsDao.getNewsById(id);
    return result;
}

export async function getNewsByAlias(alias: string) {
    return await GNewsDao.getNewsByAlias(alias);
}

export async function createNews(data: any) {
    // 检查alias是否已存在
    if (data.alias) {
        const existingNews = await GNewsDao.getNewsByAlias(data.alias);
        if (existingNews) {
            throw new Error(`别名 '${data.alias}' 已存在，请使用其他别名`);
        }
    }
    
    // 添加创建时间和更新时间
    const now = getCurrentTimestamp();
    data.created_at = now;
    data.updated_at = now;
    
    let descs = data.descs;
    delete data.descs;
    let id = await GNewsDao.createNews(data);
    if (id > 0) {
        if (descs) {
            for (let desc of descs) {
                desc.alias = data.alias;
                await GNewsDao.editNewsDesc(desc);
            }
        }
    }
    return id;
}

export async function updateNews(id: number, data: any) {
    // 检查alias是否已存在（排除当前记录）
    if (data.alias) {
        const existingNews = await GNewsDao.getNewsByAlias(data.alias);
        if (existingNews && existingNews.id !== id) {
            throw new Error(`别名 '${data.alias}' 已存在，请使用其他别名`);
        }
    }
    
    // 添加更新时间
    const now = getCurrentTimestamp();
    data.updated_at = now;
    
    let descs = data.descs;
    delete data.descs;
    if (descs) {
        for (let desc of descs) {
            desc.alias = data.alias;
            await GNewsDao.editNewsDesc(desc);
        }
    }
    
    const result = await GNewsDao.updateNews(id, data);
    
    return result;
}

export async function deleteNews(id: number) {
    const result = await GNewsDao.deleteNews(id);
    return result;
} 